package javango.forms.fields;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.inject.Inject;

import javango.forms.widgets.WidgetFactory;

public class RegexField extends CharField {

	protected String errorMessage;
	protected String regex;
	
	// cached version of the pattern
	Pattern p;
	
	@Inject
	public RegexField(WidgetFactory widgetFactory) {
		super(widgetFactory);
	}
	
	@Override
	public Object clean(String value, Map errors) {
		String cleanValue = (String)super.clean(value, errors);
		if (cleanValue == null) return null;
		
		if (p == null) return cleanValue;
		
		Matcher m = p.matcher(cleanValue);
		if (!m.matches()) {
			if (getErrorMessage() == null) {
				errors.put(getName(), "Enter a valid value");
			} else {
				errors.put(getName(), getErrorMessage());
			}
		}
		
		return cleanValue;
	}



	public String getRegex() {
		return regex;
	}

	public void setRegex(String regex) {
		p = Pattern.compile(regex);
		this.regex = regex;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

	
}
